package com.yonghui.springsecurityoauth2demo.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final ObjectMapper objectMapper;

    public CustomAuthenticationSuccessHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 获取认证成功的用户信息
        String username = authentication.getName();
        // 这里可以根据需要从认证对象中获取更多的用户信息

        // 构建要返回给前端的用户信息
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", username);
        // 可以添加其他需要返回的用户信息，例如角色、权限等

        // 将用户信息转换为 JSON 格式
        String jsonResponse = objectMapper.writeValueAsString(userInfo);

        // 设置响应类型和编码
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // 将 JSON 数据写入响应体
        response.getWriter().write(jsonResponse);
    }
}
